<?php
namespace app\index\model;
use think\Db;
/**
 * Created by Submint Text.
 * User: hetaoren<452649510@qq.com>
 * Date: 2017/03/10
 * Explain: 订单类
 */
class Orders extends Base{
     /**
      *  订单列表
      */
	public function pageQuery(){
		$areaIdPath = input('areaIdPath');
		$where = [];
		$where['o.dataFlag'] = 1;
		if($areaIdPath !='')$where['o.areaIdPath'] = ['like',$areaIdPath."%"];
		$diseaseId = input('diseaseId');
		if($diseaseId != '')$where['o.diseaseId'] = $diseaseId;
		$staffId = input('staffId');
		if($staffId != '')$where['o.staffId'] = $staffId;
		$goodsName = input('goodsName');
		if($goodsName != '')$where['o.goodsName'] = ['like',"%$goodsName%"];
		$user_name = input('user_name');
		if($user_name != '')$where['o.user_name'] = ['like',"%$user_name%"];
		$consume_type = input('consume_type');
		if($consume_type != '')$where['u.consume_type'] = $consume_type;
		$startDate = input('startDate');
		$endDate = input('endDate');
		if($startDate!='')$where['o.createTime'] = ['>=',$startDate];
		if($endDate!='')$where[' o.createTime'] = ['<=',$endDate];		
		$total0 = input('total0');
		$total1 = input('total1');
		if($total0!='')$where['o.total'] = ['>=',$total0];
		if($total1!='')$where[' o.total'] = ['<=',$total1];	
		if(session("HTR_STAFF.staffRoleId") == 2)$where['o.shopId'] = session("HTR_STAFF.shopId");
		if(session("HTR_STAFF.staffRoleId") == 3)$where['o.staffId'] = session("HTR_STAFF.staffId");
		
		$page = Db::name('Orders')->alias('o')->join('__USERS__ u','u.user_id=o.user_id','left')
		        ->where($where)->field('o.*')
		        ->order('o.orderId desc')->paginate(input('pagesize/d'))->toArray();
		// $page = $this->where($where)->order('orderId desc')->paginate(input('pagesize/d'))->toArray();
		if(count($page['Rows'])>0){
        	$diseaseList = model('disease')->where(['dataFlag'=>1])->column('diseaseId,diseaseName');
        	$staffList = model('staffs')->where(['dataFlag'=>1])->column('staffId,staffName');
			foreach ($page['Rows'] as $key => $v){
				$page['Rows'][$key]['diseaseName'] = isset($diseaseList[$v['diseaseId']]) ? $diseaseList[$v['diseaseId']] : '';
				$page['Rows'][$key]['staffName'] = isset($staffList[$v['staffId']]) ? $staffList[$v['staffId']] : '';
  				$page['Rows'][$key]['areaPathName'] = $this->areaPathName($v['areaIdPath']);
			}
		}
		$total = Db::name('Orders')->alias('o')->join('__USERS__ u','u.user_id=o.user_id','left')
		        ->where($where)->sum('o.total');
		$page['SumAmount'] = sprintf("%.2f", $total);
		return $page;
	}

	public function areaPathName($areaIdPath){
		$areaIdPath = explode('_',$areaIdPath);
		$areaPathName = '';
		foreach($areaIdPath as $v){
			if($v)$areaPathName .= ' '.model('Areas')->getNames($v);
		}
		return $areaPathName;
	}
	/**
	 * 修改库存
	 */
	public function changeStock($goodsId,$shopId,$saleNum,$type=0){
		try{
        	$stock = model('stocks')->where(['goodsId'=>$goodsId,'shopId'=>$shopId,'dataFlag'=>1])->find();
        	if(!$stock)throw \Exception('店铺没有该商品');
        	if($type == 0){
				if($stock->goodsStock < $saleNum)throw \Exception('店铺库存不足');
	        	$stock->goodsStock -= $saleNum;
	        	$stock->saleNum += $saleNum;

				$data = [];
				$data["goodsId"] = $goodsId;
				$data["shopId"] = $shopId;
				$data["type"] = $type;
				$data["num"] = $saleNum;
				$data["desc"] = '下单减库存';
				$data["createTime"] = date('Y-m-d H:i:s');
				$result = model('StockLog')->allowField(true)->save($data);
				if(false === $result)throw \Exception('日志生成失败');
        	}else{        		
	        	$stock->goodsStock += $saleNum;
	        	$stock->saleNum -= $saleNum;

				// $data = [];
				// $data["goodsId"] = $goodsId;
				// $data["shopId"] = $shopId;
				// $data["type"] = $type;
				// $data["num"] = $saleNum;
				// $data["desc"] = '编辑订单加库存';
				// $data["createTime"] = date('Y-m-d H:i:s');
				// $result = model('StockLog')->allowField(true)->save($data);
				// if(false === $result)throw \Exception('日志生成失败');
        	}
        	$result = $stock->save();
        	if(false === $result)throw \Exception('库存修改失败');
        	$goods = model('goods')->where(['goodsId'=>$goodsId])->find();
        	if(!$goods)throw \Exception('没有该商品');
        	if($type == 0){
				if($goods->goodsStock < $saleNum)throw \Exception('库存不足');
	        	$goods->goodsStock -= $saleNum;
	        	$goods->saleNum += $saleNum;
        	}else{
	        	$goods->goodsStock += $saleNum;
	        	$goods->saleNum -= $saleNum;      		
        	}
        	$result = $goods->save();
        	if(false === $result)throw \Exception('库存修改失败');  
		}catch (\Exception $e) {
            return $e->getMessage();  
            // return false; 
        }
        return true; 
	}
	/**
	 * 新增
	 */
	public function add(){
		$data = input('post.');
		$data["total"] = $data["salePrice"] * $data["saleNum"];
		if($data['createTime'] == '')$data['createTime'] = date('Y-m-d');
		HTRUnset($data, 'orderId');
		Db::startTrans();
		try{
			$result = $this->allowField(true)->save($data);
	        if(false === $result)throw \Exception('新增失败');  
		    $result = $this->changeStock($data["goodsId"],$data["shopId"],$data["saleNum"]);
		    if(true !== $result)throw \Exception($result); 	
		    $this->upUser($data['user_id']); 
        	Db::commit();
        	return HTRReturn("新增成功", 1);
		}catch (\Exception $e) {
            Db::rollback();
            return HTRReturn($e->getMessage());
        }
	}
    /**
	 * 编辑
	 */
	public function edit(){
	    return HTRReturn("不能编辑");
		$orderId = input('post.orderId/d',0);
		$data = input('post.');
		$data["total"] = $data["salePrice"] * $data["saleNum"];
		if($data['createTime'] == '')$data['createTime'] = date('Y-m-d');
		$order = $this->get($data["orderId"]);
		HTRUnset($data, 'orderId');
		Db::startTrans();
		try{
			$result = $this->allowField(true)->save($data,['orderId'=>$orderId]);
	        if(false === $result)throw \Exception('编辑失败');          	
		    $result = $this->changeStock($order->goodsId,$order->shopId,$order->saleNum,1);
		    if(true !== $result)throw \Exception($result);
		    $result = $this->changeStock($data["goodsId"],$data["shopId"],$data["saleNum"]);
		    if(true !== $result)throw \Exception($result);		     
    		if($order->user_id != $data['user_id']){
		    	$this->upUser($order->user_id); 
    		}    				    
		    $this->upUser($data['user_id']); 

	    	Db::commit();
	    	return HTRReturn("编辑成功", 1);
		}catch (\Exception $e) {
            Db::rollback();
            return HTRReturn($e->getMessage());
        }
	}

	/**
	 * 删除订单
	 */
	public function del(){
		$id = input('post.id/d');
		$order = $this->get($id);
		$order->dataFlag = -1;
		Db::startTrans();
		try{
		    $result = $order->save();		    
	        if(false === $result)throw \Exception('删除失败');          	
		    $result = $this->changeStock($order->goodsId,$order->shopId,$order->saleNum,1);
		    if(true !== $result)throw \Exception($result);  
		    $this->upUser($order->user_id);
        	Db::commit();
        	return HTRReturn("删除成功", 1);
		}catch (\Exception $e) {
            Db::rollback();
            return HTRReturn($e->getMessage());
        }
	}
	/**
	 * 修改用户
	 */
	public function upUser($user_id){
		$count = $this->where(['user_id'=>$user_id,'dataFlag'=>1])->count();
		if($count==0){
			model('users')->where('user_id',$user_id)->update(['firstTime'=>'']);
		}elseif($count==1){
			model('users')->where('user_id',$user_id)->update(['firstTime'=>date('Y-m-d')]);
		}

		$data = [];
    	$data['first_consume'] = $this->where(['user_id'=>$user_id,'dataFlag'=>1])->order('createTime asc')->value('total');
    	$data['total'] = $this->where(['user_id'=>$user_id,'dataFlag'=>1])->sum('total');
    	$diseaseId = $this->group('diseaseId')->where(['user_id'=>$user_id,'dataFlag'=>1])->order('diseaseId asc')->column('diseaseId');
    	$data['diseaseId'] = join(',',$diseaseId);
    	model('users')->where('user_id',$user_id)->update($data);

    	$last = $this->where(['user_id'=>$user_id,'dataFlag'=>1])->order('createTime desc')->find();
		model('Remind')->where(['is_read'=>0,'type'=>1,'user_id'=>$user_id])->delete();	
		if($last){
			if($last['remind']){				
				$remind = explode(',',$last['remind']);
				$_data = [];
				foreach($remind as $v){
					$remindTime = strtotime($last['createTime']) + $v * 86400;
					if($remindTime < time())continue;
					$_data[] = ['user_id'=>$user_id,'type'=>1,'day'=>$v,'remindTime'=>date('Y-m-d',$remindTime)];
				}
				model('Remind')->insertAll($_data);	   					
			}
		}
	}
}
